package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //注入request对象
    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 添加排除方法：如果请求路径以/member开头，就排除掉
     */
    @SneakyThrows
    //@SneakyThrows 是 Lombok 提供的一个“偷懒”注解，它的作用可以一句话概括：把方法里可能抛出的受检异常（checked exception）悄悄吃掉，编译时不用再写 try-catch，也不用再 throws 声明。
    public boolean isExclude(){
        try {
            String requestURI = httpServletRequest.getRequestURI();
            if (requestURI.startsWith("/member")){
                return true;
            }
            return false;
        } catch (Exception e) {
            return true;
        }
    }


    // 插入数据时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        //只有非排除的请求路径 才要设置createBy
        if (!isExclude()){
        this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUserId()));
        }
    }

    // 修改数据时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
        //只有非排除的请求路径 才要设置updateBy
        if (!isExclude()){
        this.setFieldValByName("updateBy", String.valueOf(getLoginUserId()), metaObject);
        }
    }

    // 获取当前登录人的id
    public Long getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
            return 1L;
        } catch (Exception e) {
            return 1L;
        }
    }
}
